import axios from 'axios'
import {getRedirectPath} from '../util';

const ERROR_MSG = 'ERROR_MSG';
const LOGOUT = 'LOGOUT'
const AUTH_SUCCESS = 'AUTH_SUCCESS'
const LOAD_DATA='LOAD_DATA';
//用户的初始状态
const initState={
    redirectTo:'',
    msg:'',
    user:'',
    type:''
}
//REDUCER
export function user(state=initState,action){
    switch(action.type){
        case AUTH_SUCCESS:
        return {...state,msg:'', redirectTo:getRedirectPath(action.payload), ...action.payload}
        case LOAD_DATA:
        return {...state,...action.payload}
        case ERROR_MSG:
        return {...state,isAuth:false,msg:action.msg}
        case LOGOUT:
        return {...initState,redirectTo:'/login'}
        default:
        return state
    }
}
//错误提示的action
function errorMsg(msg){
   return {msg, type:ERROR_MSG}
}
//完善信息的action
function authSuccess(data) {
    const {pwd,...obj} = data
    return {type:AUTH_SUCCESS, payload:obj}
} 
//删除redux数据
export function logoutSubmit() {
    return {type:LOGOUT}
} 
//获取登录信息
export function loadData(userinfo) {
    return {type:LOAD_DATA,payload:userinfo}
}

//登录
export function login({user,pwd}){
    if(!user||!pwd){
        return errorMsg('用户名和密码必须输入')
    }
    return dispatch=>{
        axios.post('/user/login',{user,pwd})
        .then(res=>{
            if(res.status===200&&res.data.code===0){
             //请求成功
             dispatch(authSuccess(res.data.data))
            }else{
             //失败
             dispatch(errorMsg(res.data.msg))
            }
        })
   }
}
//注册
export function register({user,pwd,repeatpwd,type}) {
    if(!user||!pwd||!type) {
        return errorMsg('用户名密码必须输入');
    }
    if (pwd!==repeatpwd) {
        return errorMsg('确认密码输入有误');
    }
    return dispatch=>{
         axios.post('/user/register',{user,pwd,type})
         .then(res=>{
             if(res.status===200&&res.data.code===0){
              //请求成功
              dispatch(authSuccess({user,pwd,type}))
             }else{
              //失败
              dispatch(errorMsg(res.data.msg))
             }
         })
    }
}
//完善注册信息
export function update(data){
    return dispatch=>{
        axios.post('/user/update',data)
        .then(res=>{
            if(res.status===200&&res.data.code===0){
             //请求成功
             dispatch(authSuccess(res.data.data))
            }else{
             //失败
             dispatch(errorMsg(res.data.msg))
            }
        })
    }
}
